package org.itew.mymapreduce.core.impl;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

import org.itew.mymapreduce.core.DataCollection;
import org.itew.mymapreduce.core.Merger;

public class SimpleMerger<K,V> implements Merger<K, V> {
	
	private static class MultiDataCollection<K,V> implements DataCollection<K,V>{
		
		private final Collection<DataCollection<K, V>> collections;
		
		public MultiDataCollection(Collection<DataCollection<K, V>> collections)
		{
			this.collections = collections;
		}
		
		@Override
		public void collect(K key, V value) {
			throw new UnsupportedOperationException("this method is unsupported:MultiDataCollection.collect(K key, V value)");
		}

		@Override
		public Set<K> keySet() {
			//合并key的值
			Set<K> keySet = new HashSet<K>();
			
			for(DataCollection<K,?> amap: collections){
				keySet.addAll(amap.keySet());
			}
			
			
			return keySet;
		}

		@Override
		public Collection<V> getValues(K key) {
			
			Collection<V> values = new LinkedList<V>();
			for(DataCollection<K,V> collection : collections){
				
				Collection<V> collectionA = collection.getValues(key);
				
				if(collectionA!=null)
					values.addAll(collectionA);
				
			}
			
			return values;
		}
		
	}
	

	@Override
	public DataCollection<K, V> merge(Collection<DataCollection<K, V>> collections) {
		
		return new MultiDataCollection<K, V>(collections);
		
	}

}
